package handler

import (
	"fmt"
	"time"
	"os"
	"path/filepath"
	"io"
	"github.com/henrylee2cn/faygo"
	"strconv"
	"strings"
)

var Index = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/index.html", faygo.Map{
		"name": ctx.GetSession("admin"),
		"count1": func() int {
			row, err := Engine.Count(News{})
			fmt.Println("统计公告", row, err)
			return int(row)
		},
		"count2": func() int {
			row, err := Engine.Count(Staff{})
			fmt.Println("统计员工", row, err)
			return int(row)
		},
		"count3": func() int {
			row, err := Engine.Count(Email{})
			fmt.Println("统计申请", row, err)
			return int(row)
		},
		"count4": func() int {
			row, err := Engine.Count(Reply{})
			fmt.Println("统计留言", row, err)
			return int(row)
		},
	})
})

var Home = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	fmt.Println("返回登录页,销毁Seesion")
	ctx.DestroySession()
	return ctx.Render(200, "view/home.html", faygo.Map{})
})

func (tmpObj *Admin) Serve(ctx *faygo.Context) error {
	if exist, err := Engine.Exist(tmpObj); exist && err == nil {
		ctx.SetSession("admin", tmpObj.Username)
		fmt.Println("管理员成功登录")
		return ctx.Redirect(301, "/index")
	} else {
		fmt.Println("管理员失败登录")
		return Home(ctx)
	}
}

func (tmpObj *Staff) Serve(ctx *faygo.Context) error {
	option := ctx.Param("option")
	switch option {
	case "CCC":
		fmt.Println("新建数据", tmpObj)
		row, err := Engine.Omit("create_time", "id", "status").InsertOne(tmpObj)
		fmt.Println("CCC", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "UUU":
		fmt.Println("更新数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Omit("create_time").Update(tmpObj)
		fmt.Println("UUU", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "RRR":
		fmt.Println("查询数据", tmpObj)
		var obj = Staff{Id: tmpObj.Id}
		exist, err := Engine.Get(&obj)
		fmt.Println("RRR", exist, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"obj": obj,
			"err": err,
		})
	case "DDD":
		fmt.Println("删除数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Delete(Staff{Id: tmpObj.Id})
		fmt.Println("DDD", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	default:
		return ctx.JSON(200, faygo.Map{"err": "CURD操作失败!"})
	}
}

var Release = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/release.html", faygo.Map{
		"author": ctx.GetSession("admin"),
		"type":   0,
		"list":   func() (list []News) { Engine.Where("type != 1").Desc("create_time").Find(&list); return list },
	})
})

var Release2 = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/release.html", faygo.Map{
		"author": ctx.GetSession("admin"),
		"type":   1,
		"list":   func() (list []News) { Engine.Where("type = 1").Desc("create_time").Find(&list); return list },
	})
})

func (tmpObj *News) Serve(ctx *faygo.Context) error {
	option := ctx.Param("option")
	switch option {
	case "CCC":
		fmt.Println("新建数据", tmpObj)
		row, err := Engine.Omit("create_time", "id").InsertOne(tmpObj)
		fmt.Println("CCC", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "UUU":
		fmt.Println("更新数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Update(tmpObj)
		fmt.Println("UUU", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "RRR":
		fmt.Println("查询数据", tmpObj)
		var obj = News{Id: tmpObj.Id}
		exist, err := Engine.Get(&obj)
		fmt.Println("RRR", exist, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"obj": obj,
			"err": err,
		})
	case "DDD":
		fmt.Println("删除数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Delete(News{Id: tmpObj.Id})
		fmt.Println("DDD", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	default:
		return ctx.JSON(200, faygo.Map{"err": "CURD操作失败!"})
	}
}

var StaffList = faygo.HandlerFunc(func(ctx *faygo.Context) error {

	return ctx.Render(200, "view/staff.html", faygo.Map{
		"list3": func() (list []Staff) {
			var stafflist []Staff
			Engine.Desc("create_time").Find(&stafflist)
			for _, v := range stafflist {
				if len(v.Ident) > 9 && v.Status != 2 {
					fmt.Println("检查未退休的职工")
					var str = v.Ident[6:10]
					y, err := strconv.Atoi(str)
					if err != nil {
						fmt.Println("无效的身份证,无法提取出生年份", str)
						continue
					} else {
						fmt.Println("提取出生年份", y)
						if time.Now().Year()-y == 59 {
							fmt.Println(time.Now().Year(), y, v.Username)
							fmt.Println("即将的退休职工")
							list = append(list, v)
						} else {
							fmt.Println(time.Now().Year(), y, v.Username)
							fmt.Println("未的退休职工")
						}
						if len(v.Ident) > 9 && v.Status != 2 {
							fmt.Println("检查未退休的职工")
							var str = v.Ident[6:14]
							y, err := strconv.Atoi(str)
							if err != nil {
								fmt.Println("无效的身份证,无法提取出生年份", str)
								continue
							} else {
								yy, _ := strconv.Atoi(time.Now().Format("20060102"))
								fmt.Println(yy, y)
								if yy-y >= 600000 {
									fmt.Println("新的退休职工")
									v.Status = 2
									r, e := Engine.ID(v.Id).Update(&v)
									fmt.Println("更新检查", r, e)
								} else {
									fmt.Println("未退休职工")
									v.Status = 1
									r, e := Engine.ID(v.Id).Update(&v)
									fmt.Println("更新检查", r, e)
								}
							}
						}
					}
				}
			}
			return list
		}, //即将退休
		"list":  func() (list []Staff) { Engine.Desc("create_time").Find(&list, Staff{Status: 1}); return list },
		"list2": func() (list []Staff) { Engine.Desc("create_time").Find(&list, Staff{Status: 2}); return list },
	})
})

var CheckRequest = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/email.html", faygo.Map{
		"list":  func() (list []Email) { Engine.Desc("create_time").Find(&list, Email{State: 1}); return list },
		"list2": func() (list []Email) { Engine.Desc("create_time").Find(&list, Email{State: 2}); return list },
	})
})

func (tmpObj *Email) Serve(ctx *faygo.Context) error {
	option := ctx.Param("option")
	switch option {
	case "CCC":
		fmt.Println("新建数据", tmpObj)
		row, err := Engine.Omit("create_time", "id").InsertOne(tmpObj)
		fmt.Println("CCC", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "UUU":
		fmt.Println("更新数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Omit("create_time").Update(tmpObj)
		fmt.Println("UUU", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "RRR":
		fmt.Println("查询数据", tmpObj)
		var obj = Email{Id: tmpObj.Id}
		exist, err := Engine.Get(&obj)
		fmt.Println("RRR", exist, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"obj": obj,
			"err": err,
		})
	case "DDD":
		fmt.Println("删除数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Delete(Email{Id: tmpObj.Id})
		fmt.Println("DDD", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	default:
		return ctx.JSON(200, faygo.Map{"err": "CURD操作失败!"})
	}
}

var Replylist = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/reply.html", faygo.Map{
		"list": func() (list []Reply) { Engine.Desc("create_time").Find(&list); return list },
	})
})

var Filemanager = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	var list []file
	filepath.Walk("./upload", func(path string, f os.FileInfo, err error) error {
		if !f.IsDir() {
			path = strings.Replace(path, "upload", "", 1)
			path = strings.Replace(path, "/", "", 1)
			path = strings.Replace(path, "\\", "", 1)
			var tmp = file{path, f.ModTime().Format("2006-01-02 15:04"), path}
			list = append(list, tmp)
			fmt.Println(path)
		}
		return nil
	})
	return ctx.Render(200, "view/filelist.html", faygo.Map{
		"list": list,
		"name": ctx.GetSession("admin").(string),
	})
})

var DeleteFile = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	filename := ctx.Param("name")
	err := os.Remove("upload/" + filename)
	fmt.Println("删除文件出现错误", err)
	return ctx.JSON(200, faygo.Map{
		"error": err,
	})
})

var Uploadfile = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	img, h, rerr := ctx.FormFile("file")
	fmt.Println("接收文件检查", rerr)
	if rerr == nil {
		_, err := os.Open("upload/" + h.Filename)
		if err == nil {
			os.Remove("upload/" + h.Filename)
		}
		f, ferr := os.Create("upload/" + h.Filename)
		fmt.Println("创建文件检查:", ferr)
		defer f.Close()
		io.Copy(f, img)
	}
	return ctx.JSON(200, faygo.Map{
		"error": rerr,
	})
})

func DayMission() {
	for {
		now := time.Now()
		next := time.Date(now.Year(), now.Month(), now.Day()+1, 6, 0, 0, 0, now.Location())
		fmt.Println("下一个时刻", next)
		fmt.Println("时差", next.Unix()-now.Unix())
		var c = next.Unix() - now.Unix()
		t := time.NewTimer(time.Second * time.Duration(c))
		func() {
			fmt.Println("该干活了")
			var stafflist []Staff
			Engine.Find(&stafflist)
			for _, v := range stafflist {
				if len(v.Ident) > 9 && v.Status != 2 {
					fmt.Println("检查未退休的职工")
					var str = v.Ident[6:14]
					y, err := strconv.Atoi(str)
					if err != nil {
						fmt.Println("无效的身份证,无法提取出生年份", str)
						continue
					} else {
						yy, _ := strconv.Atoi(time.Now().Format("20060102"))
						fmt.Println(yy, y)
						if yy-y >= 600000 {
							fmt.Println("新的退休职工")
							v.Status = 2
							r, e := Engine.ID(v.Id).Update(&v)
							fmt.Println("更新检查", r, e)
						} else {
							fmt.Println("未退休职工")
							v.Status = 1
							r, e := Engine.ID(v.Id).Update(&v)
							fmt.Println("更新检查", r, e)
						}
					}
				}
			}

		}()
		<-t.C
	}
}

var Rencai = faygo.HandlerFunc(func(ctx *faygo.Context) error {
	return ctx.Render(200, "view/rencai.html", faygo.Map{
		"list": func() (list []Rc) {
			Engine.Find(&list)
			return list
		},
	})
})

func (tmpObj *Rc) Serve(ctx *faygo.Context) error {
	option := ctx.Param("option")
	switch option {
	case "CCC":
		fmt.Println("新建数据", tmpObj)
		row, err := Engine.Omit("create_time", "id").InsertOne(tmpObj)
		fmt.Println("CCC", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "UUU":
		fmt.Println("更新数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Omit("create_time").Update(tmpObj)
		fmt.Println("UUU", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	case "RRR":
		fmt.Println("查询数据", tmpObj)
		var obj = Rc{Id: tmpObj.Id}
		exist, err := Engine.Get(&obj)
		fmt.Println("RRR", exist, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"obj": obj,
			"err": err,
		})
	case "DDD":
		fmt.Println("删除数据", tmpObj)
		row, err := Engine.ID(tmpObj.Id).Delete(Rc{Id: tmpObj.Id})
		fmt.Println("DDD", row, err, tmpObj)
		return ctx.JSON(200, faygo.Map{
			"row": row,
			"err": err,
		})
	default:
		return ctx.JSON(200, faygo.Map{"err": "CURD操作失败!"})
	}
}

var Homepage = faygo.HandlerFunc(func(ctx *faygo.Context)error {
	return ctx.Render(200,"view/zhuye.html",faygo.Map{
		"list1": func() (list []News) { Engine.Desc("create_time").Find(&list); return list },
		"list2": func() (list []Email) { Engine.Desc("create_time").Find(&list); return list },
		"list3": func() (list []Rc) { Engine.Find(&list); return list },
	})

})